// CloudSponge.com JavaScript Library v0.9.4 Beta
// http://www.cloudsponge.com
// Copyright (c) 2010 Cloud Copy, Inc.
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
// 
// Written by Graeme Rouse
// graeme@cloudsponge.com
// For Duytan at Net-a-Porter
// This library is no longer actively supported, please consider using the Cloudsponge widget instead.

/*
 * Usage:
 * Include this file on the import page:
 *  e.g. <script type='text/javascript' src='csimport.js'></script>
 * 
 * Define the following constant values 
 * DOMAIN_KEY = "<Your CloudSponge.com domain key>";
 * DOMAIN_PASSWORD = "<Your CloudSponge.com domain password>";
 * 
 * Create the following callback functions
 * function update_event(event) {} // optional
 * Parameters:
 *  event - a single event object. This may be an error event.
 *    e.g. {'status':'INPROGRESS', 'event_type':'GATHERING', 'value':42}
 *      OR {'status':'ERROR', 'event_type':'GATHERING', 'value':0x101, 'description':'Could not import from <service>: <reason>.'}
 *    (see CloudSponge.com integration document for more information regarding events)
 * function update_contacts(contacts) {} // required
 *  contacts - an array of contacts returned for this user's account or an error object
 *    e.g. [
 *          {
 *            "first_name":"John", "last_name":"Doe", 
 *            "phone": [{"number":"555-1234","type":"Home"}, {"number":"555-2468","type":"Work"}],
 *            "email": [{"address":"johndoe@nowhere.com","type":"Email 1"}, {"address":"second@email.com","type":"Email 2"}] 
 *          }, 
 *          { 
 *            "first_name":"Jane", "last_name":"Smith", 
 *            "phone":[{"number":"555.5678","type":"Home"}], 
 *            "email":[{"address":"janesmith@nowhere.com","type":"Email 1"}] 
 *          } 
 *        ] 
 *    (see CloudSponge.com integration document for more information regarding contacts)
 * 
 * Call the open_popup function to drive the import process.
 *  e.g. open_popup('yahoo');
 *    OR open_popup('aol', true, 'user', 'password')
 *
 */

var event_interval = null;
// Public function to open the popup window and initiate the import. 
// Parameters:
//  service: (required, case-sensitive) the name of the service to call, 
//            one of [yahoo, windowslive, gmail, aol, plaxo, outlook, addressbook]
//  hide: (optional, default = false) boolean indicating if the popup window should be hidden in the background
//  username: (optional) string containing the end user's account username (only applicable for aol or plaxo)
//  password: (optional) string containing the end user's account password (only applicable for aol or plaxo)
function open_popup(service, hide, username, password) {
  // stop the current interval if it is running
  if (event_interval) {
    clearTimeout(event_interval);
  }
  
  initialize_globals();
  
  // capture the global value in the parent
  input_service = service;
  
  // Set the popup size depending on the target
  popup_height = popup_specifications[service]['popup_height'];
  popup_width = popup_specifications[service]['popup_width'];
  url_action = popup_specifications[service]['url_action'];

  // open a blank popup window
  popup = window.open('', "_blank", 'height='+popup_height+',width='+popup_width+',location=no,menubar=no,resizable=no,status=no,toolbar=no');
  // write content to the popup
  content = '<html><head>';
  content += '<scr'+'ipt type="text/javascript" src="jquery-1.4.2.min.js"></scr'+'ipt>';
  content += '</head><body><p>Your contacts are being imported now. Please do not close this window or the import process will be interrupted. </p>\n';
  if (url_action == 'desktop_applet') {
    content += '<div id="applet_tag"></div>\n';
  }
  content += '<scr'+'ipt type="text/javascript">';
  content += "var user_consent_callback = function(json){\n";
  content += "  if (json.status == 'success'){ \n";
  content += "    window.opener.import_id = json.id;\n";
  content += "    window.opener.consent_url = json.url;\n";
  if (url_action == 'user_consent') {
    content += "    window.location = json.url;\n";
  } else if (url_action == 'desktop_applet') {
    content += "    $('#applet_tag').append('<APPLET archive=\"' + json.url + '\" code=\"ContactsApplet\" id=\"Contact_Importer\" width=\"0\" height=\"0\"><PARAM name=\"cookieValue\" value=\"document.cookie\"/><PARAM name=\"importActionID\" value=\"' + json.id + '\">Your browser does not support Java which is required for this utility to operate correctly.</APPLET>');\n";
  } else if (url_action == 'import') {
    content += " window.close();\n";
  }
  content += "  } else { alert('Could not begin import: [' + json.message + ']');} };\n";
  content += "function begin_import(){$.ajax({url: '" + API_ROOT + "begin_import/"+url_action+"?callback=user_consent_callback', dataType: 'jsonp', type: 'GET', data: {service:window.opener.input_service, domain_key:window.opener.DOMAIN_KEY, domain_password:window.opener.DOMAIN_PASSWORD, username:'"+username+"', password:'"+password+"'}, jsonpCallback:'user_consent_callback', cache:false});};\n";
  content += "function test_readiness(){ (typeof $ == 'undefined') ? setTimeout('test_readiness()',100) : begin_import(); };\n"
  content += "test_readiness();\n"// This is a hack to let IE load jquery.js javascript file in time before this gets called. the issue should be mitigated when using the compressed version of the js file.
  content += '</scr'+'ipt>\n';
  content += '</body></html>\n';
  popup.document.writeln(content);
  
  
  if (!hide) {
    popup.focus();
  }
  else {
    window.focus();
  }
  
  event_interval = setTimeout(get_events, UPDATE_INTERVAL*1000);
  
  return (undefined === popup);
}


// Public Constants
// var DOMAIN_KEY = 'CHANGEME!';
// var DOMAIN_PASSWORD = 'CHANGEME!';
var API_ROOT = 'https://api.cloudsponge.com/'

// internal constants
var TIMEOUT_LIMIT = 180; // number of seconds to consider the request timed out after
var UPDATE_INTERVAL = 4;
// Private state variables
var timeout_limit = TIMEOUT_LIMIT;
var input_service = '';
var import_id;
var get_contacts_interval;
var popup;
var completed = false;

//
var popup_specifications = {
  'yahoo':        {'popup_height':'500', 'popup_width':'500', 'url_action':'user_consent'},
  'gmail':        {'popup_height':'600', 'popup_width':'987', 'url_action':'user_consent'},
  'windowslive':  {'popup_height':'600', 'popup_width':'987', 'url_action':'user_consent'},
  'plaxo':        {'popup_height':'600', 'popup_width':'987', 'url_action':'import'},
  'aol':          {'popup_height':'600', 'popup_width':'987', 'url_action':'import'},
  'outlook':      {'popup_height':'500', 'popup_width':'500', 'url_action':'desktop_applet'},
  'addressbook': {'popup_height':'500', 'popup_width':'500', 'url_action':'desktop_applet'}
}

function initialize_globals() {
  timeout_limit = TIMEOUT_LIMIT;
  input_service = '';
  import_id = undefined;
  popup = undefined;
  completed = false;
}

var user_consent_callback = function(json){
  if (json.status == 'success'){
    import_id = json.id;
    consent_url = json.url;
    // open a dhtml popup and populate it with the consent_url
    // alert('user_consent_callback:' + $.toJSON(json));
    window.open(consent_url, 'get_consent'); // can it be done? no...
    // then periodically GET the contacts api to see if they are ready yet.
    // get_contacts_interval = setInterval('get_contacts()',2000);
  } else {
    alert('Could not begin import: [' + json.message + ']');
  }
}

function get_contacts() {
  if (import_id) { 
    $.ajax({
      url: API_ROOT + 'contacts',
      dataType: 'jsonp',
      cache:false,
      jsonpCallback:'get_contacts_callback',
      type: 'GET',
      data: {id:import_id, domain_key:DOMAIN_KEY, domain_password:DOMAIN_PASSWORD}
    });
  }
}

// calls the 'update_contacts' callback function with the returned contacts.
var get_contacts_callback = function(json) {
  completed = true;
  timeout_limit = TIMEOUT_LIMIT;
  
  // stop the periodic call to get contacts
  // clearInterval(window.get_contacts_interval);
  if (!popup.closed) {
    popup.close();
  }
  window.focus();
  //  render the contacts in the browser
  if (json && typeof update_contacts == 'function') {
    update_contacts(json);
  }
}

function get_events() {
  timeout_limit = timeout_limit - UPDATE_INTERVAL;
//  if (popup.closed) {
//    update_contacts({error:'You must grant consent to import your contacts.'})
//  } else 
if (timeout_limit < 0) {
    update_contacts({error:'Time limit exceeded. Please try again.'});
  } else if (import_id) {
    $.ajax({
      url: API_ROOT + 'events',
      dataType: 'jsonp',
      cache:false,
      jsonpCallback:'get_events_callback',
      type: 'GET',
      data: {id:import_id, domain_key:DOMAIN_KEY, domain_password:DOMAIN_PASSWORD}
    });
  } else {
    // call self again when the import_id is available
    event_interval = setTimeout(get_events, UPDATE_INTERVAL*1000);
  }
}

// called when events are captured from the remote server
// calls the callback function 'update_event' with each event object received.
var get_events_callback = function(json) {
  var error = false;

  // check the event to see if we have completed or encountered an error
  if (json['events']) {
    for (i = 0;  i < json['events'].length; i++) {
      e = json['events'][i];
      if (e['status'] == 'ERROR') {
        // We encountered an error, stop and report the error
        error = true;
        completed = true;
      } else if (e['event_type'] == 'COMPLETE' && e['status'] == 'COMPLETED') {
        // Import is complete and successful, get the contacts
        completed = true;
        get_contacts();
      }
      if (typeof update_event == 'function') {
        // Update the browser with the current event / error
        update_event(e);
      }
    }
  }
  if (!completed && !error) {
    event_interval = setTimeout(get_events, UPDATE_INTERVAL*1000);
  }
}

